package com.llh.uua.util

import com.llh.uua.model.SysRole
import com.llh.uua.model.SysUser
import com.llh.uua.model.dto.AccountDto
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails

/**
 *
 *
 * Created At 2021/3/22 22:15
 * @author llh
 */
@SpringBootTest
internal class JwtUtilTest {

    private lateinit var userDetails: UserDetails

    /**
     * Test init data
     */
    @BeforeEach
    fun `test init data`() {
        val user = SysUser {
            username = "Tom"
            password = "1234"
            enabled = true
        }
        val role = SysRole {
            roleName = "admin"
        }
        val role2 = SysRole {
            roleName = "ceo"
        }
        val role3 = SysRole {
            roleName = "cto"
        }
        val details = AccountDto(user)
        details.addAuthorityForRole(role)
        details.addAuthorityForRole(role2)
        details.addAuthorityForRole(role3)
        userDetails = details
    }

    /**
     * Test create token
     */
    @Test
    fun `test create token`() {
        val accessToken = createAccessToken(userDetails)
        val refreshToken = createRefreshToken(userDetails)

        validateAccessToken(accessToken)
        validateRefreshToken(refreshToken)
        val token = buildAccessTokenWithRefreshToken(refreshToken)
        token?.let {
            println("buildAccessTokenWithRefreshToken: $it")
            validateAccessToken(it)
        }
        assertEquals(token != null, true)
    }

    /**
     * Test parse claims
     */
    @Test
    fun `test parse claims`() {
        val accessToken = createAccessToken(userDetails)
        val authorities = parseClaimsAccessToken(accessToken)
            ?.get(JWT_AUTHORITY_KEY)
            ?.let { it as List<*> }
        val simpleAuthList = authorities?.map { it.toString() }
            ?.map { SimpleGrantedAuthority(it) }

        assertTrue(authorities != null)
        assertTrue(simpleAuthList != null)
    }
}